from prometheus_client import start_http_server, Gauge
import requests
import time
import json
import os
import logging

# 配置日志记录  
logging.basicConfig(  
    level=logging.INFO,  # 设置日志级别为 DEBUG  
    format='%(asctime)s - %(levelname)s - %(message)s',  # 日志格式  
    handlers=[  
        # logging.FileHandler('app.log'),  # 将日志输出到文件  
        logging.StreamHandler()  # 也输出到控制台  
    ]  
)  

#  读取接口文件
current_directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_directory, 'urllist.json')  
with open(file_path, 'r') as file:  
    data = json.load(file)  
endpoints = data['items']

# 用于存储动态创建的指标
metrics = {}

def fetch_data_from_api(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()  # 假设返回 JSON 数据
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data from {url}: {e}")
        return None

def create_or_update_metrics(endpoint, data):
    metric_name = endpoint['name']
    data_field = endpoint['data_status_field']
    if metric_name not in metrics:
      metrics[metric_name] = Gauge(metric_name, f'Description of {metric_name}')
    metrics[metric_name].set(data[data_field])

def update_metrics():
    while True:
        for endpoint in endpoints:
            data = fetch_data_from_api(endpoint['url'])
            if data:
                logging.info('接口%s信息更新成功' %endpoint['name'])
                create_or_update_metrics(endpoint, data)
                print("更新数据成功")
            else:
                logging.error('接口%s信息更新失败' %endpoint['name'])
        time.sleep(60)  # 每隔 60 秒更新一次数据

if __name__ == '__main__':
    logging.info('服务启动') 
    # 启动 HTTP 服务器，监听 8000 端口
    start_http_server(80)
    # 更新指标数据
    update_metrics()